declare type operateType = "insert" | "update" | "delete" | "add" | "query";
declare type tableNameType = "animation" | "info" | "menu" | "user" | "picture" | "user_temp" | "upload_logs" | "applet_config" | "login_log" | "role";

enum tableIdName {
  animation = "aid",
  info = "iid",
  menu = "mid",
  user = "uid",
  picture = "pid",
  user_temp = "utid",
  upload_logs = "ulid",
  applet_config = "acid",
  login_log = "llid",
  role = "rid",
}

/**
 * 生成SQL语句
 * @param tableName 表名 
 * @param operateType 操作类型 insert update delete add
 * @param data 增加、更新、插入操作的数据
 * @returns 
 */
export const generateSql = (tableName: tableNameType, operate: operateType, data?: Object | Array<Object>) => {
  let sql = "";
  try {
    switch (operate) {
      case "insert":
        let columns = ""; // 列名
        let placeholdersPerRow = ""; // 数据占位符
        if (Array.isArray(data)) {
          if (data.length === 0) return "";
          const keys = Object.keys(data[0]);
          columns = keys.join(', ');
          const str = "(" + keys.map(() => '?').join(', ') + ")";
          placeholdersPerRow = Array(data.length).fill(str).join(', ');
        } else {
          if (Object.keys(data).length === 0) return "";
          const keys = Object.keys(data);
          columns = keys.join(', ');
          placeholdersPerRow = "(" + keys.map(() => '?').join(', ') + ")";
        }
        sql = `INSERT INTO ${tableName} (${columns}) VALUES ${placeholdersPerRow}`;
        break;
      case "update":
        // 更新只有单行
        let columnValues = ""; // 列名
        if (Array.isArray(data)) {
          if (data.length === 0 || data.length > 1) return "";
        } else {
          if (Object.keys(data).length === 0) return "";
          const keys = (Object.keys(data).reduce((pre: string[], key: string) => {
            pre.push(`${key} = ?`);
            return pre;
          }, []));
          columnValues = keys.join(', ');
        }
        sql = `UPDATE ${tableName} set ${columnValues}`;
        sql += ` WHERE ${tableIdName[tableName]} = "${data[tableIdName[tableName]]}"`;
        break;
      case "query":
        sql = `SELECT * FROM ${tableName}`;
        if (Array.isArray(data)) {
          sql = "";
        } else if (data && "condition" in data && data.condition) { // 从service业务中传进来的自定义条件
          sql += ` ${data.condition}`;
        }
        break;
      case "delete":
        sql = `DELETE FROM ${tableName}`;
        if (Array.isArray(data)) {
          sql = "";
        } else if ("condition" in data && data.condition) { // 从service业务中传进来的自定义条件
          sql += ` WHERE ${data.condition}`;
        }
        break;
      default:
        break;
    }
  } catch (error) {
    return "";
  }
  return sql;
}
